package com.longy.gulimall.product.mq;

import javax.jms.*;

import org.apache.activemq.command.ActiveMQMessage;
import org.apache.activemq.command.ActiveMQTextMessage;
import org.apache.activemq.util.ByteSequence;
import org.springframework.jms.support.converter.MessageConversionException;
import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.HashMap;

@Component
public class JsonMessageConverter implements MessageConverter {

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public Message toMessage(Object object, Session session) throws JMSException, MessageConversionException {
        try {
            String jsonString = objectMapper.writeValueAsString(object);
            TextMessage textMessage = session.createTextMessage();
            textMessage.setText(jsonString);
            return textMessage;
        } catch (Exception e) {
            throw new MessageConversionException("Failed to convert object to message", e);
        }
    }

    @Override
    public Object fromMessage(Message message) throws JMSException, MessageConversionException {
        try {
            if (message instanceof MapMessage) {
                MapMessage mapMessage = (MapMessage) message;
                String jsonString = mapMessage.getString("json");
                return jsonString; // 替换YourClass为你的实际类
            } else if (message instanceof ActiveMQTextMessage){
                ActiveMQTextMessage testMessage = (ActiveMQTextMessage) message;
                String text = testMessage.getText();
                return text;
            }else{
                throw new MessageConversionException("Unsupported message type: " + message.getClass().getName());
            }
        } catch (Exception e) {
            throw new MessageConversionException("Failed to convert message to object", e);
        }
    }
}
